var _ = require('lodash');
var logger = require('log4js').getLogger();

var messageBroker = {};
messageBroker.msgList = {}; //{'msg1':{socket_id,socket_id,...}}

messageBroker.order = function (data) {
    //data:{'msgName':'','socketID':''}
    var msgList = messageBroker.msgList[data.msgName];
    if(typeof(msgList) != 'undefined' && msgList.indexOf(data.socketID) >= 0){
        return true;
    }
    if (typeof(msgList) != 'undefined') {
        msgList.push(data.socketID);
    } else {
        msgList = [];
        msgList.push(data.socketID);
    }
    messageBroker.msgList[data.msgName] = msgList;
};

messageBroker.disorder = function (data) {
    var msgList = messageBroker.msgList[data.msgName] || [];
    _.remove(msgList, function (socketID) {
        return socketID == data.socketID;
    });
};

messageBroker.emit = function (msgName, data) {
    var msgList = messageBroker.msgList[msgName];  //所有订阅了msgName 的 socket 的id
    var sockets = require('./socketserver.js').sockets;
    var orderList = [];
    if (msgList) {
        sockets.map(function (socket) {
            msgList.map(function (id) {
                if (socket.client.id == id) {
                    orderList.push(socket);
                }
            })
        });
        orderList.map(function (socket) {
            socket.emit(msgName, data);
        });
        //if(type == 'task') {delete task from msglist}
        if(data.task_id){
            delete messageBroker.msgList[msgName];
        }
    }
};

//messageBroker.on = function(msgName){
//
//};


module.exports = messageBroker;